package com.hbx.gift.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.hbx.gift.dto.UserPhoneRegisterDto;
import com.hbx.gift.service.IUserService;
import com.hbx.gift.domain.User;
import com.hbx.gift.query.UserQuery;
import com.hbx.gift.util.AjaxResult;
import com.hbx.gift.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;

    /**
     * 保存和修改公用的
     * @param user 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user) {
        if ( user.getId() != null)
            userService.updateById(user);
        else
            userService.insert(user);
        return AjaxResult.success();
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        userService.deleteById(id);
        return AjaxResult.success();
    }

    //获取用户
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id") Long id) {
        User user =userService.selectById(id);
        return AjaxResult.success(user);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping
    public AjaxResult list() {
        List< User> list = userService.selectList(null);
        return AjaxResult.success(list);
    }


    /**
    * 分页查询数据
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody UserQuery query) {
        Page<User> page = new Page<>(query.getPage(), query.getRows());
        page = userService.selectPage(page);
        PageList<User> pageList = new PageList<>(page.getTotal(), page.getRecords());
        return AjaxResult.success(pageList);
    }

    //发送注册验证码
    @GetMapping("/validCode/register/{phone}")
    public AjaxResult sendRegisterVerifyCode(@PathVariable("phone")String phone){
        return userService.sendRegisterVerifyCode(phone);
    }
    //注册
    @PostMapping("/register/phone")
    public AjaxResult registerPhone( @Valid @RequestBody UserPhoneRegisterDto dto){

        return  userService.registerPhone(dto);
    }

    /**
     * 返回验证码图片
     * @param imageCodeKey
     * @return
     */
    @GetMapping("/image/{imageCodeKey}")
    public AjaxResult getVerifyCodeImage(@PathVariable("imageCodeKey") String imageCodeKey) {
        String base64 = userService.getVerifyCodeImage(imageCodeKey);
        return AjaxResult.success(base64);
    }
}
